import imageio
import numpy as np

import os
class Img2Array:
    def __init__(self) -> None:
        pass
    def main(self,src,dst):        
        with open(src, 'r') as f:  # 读取图片列表
            list = f.readlines()
        data = []
        labels = []
        base=os.path.dirname(__file__)
        for i in list:
            name, label = i.strip('\n').split(' ')  # 将图片列表中的每一行拆分成图片名和图片标签
            print(name + ' processed')
            name=os.path.join(base,name)
            img = imageio.imread(name) # 将图片读取出来，存入一个矩阵
            img = img/255 # 将图片转换为只有0、1值的矩阵
            img.resize((img.size, 1))  # 为了之后的运算方便，我们将图片存储到一个img.size*1的列向量里面
            data.append(img)
            labels.append(int(label))

        print('write to npy')
        np.save(dst, [data, labels])  # 将训练数据以npy的形式保存到成本地文件
        print('completed')

if __name__=='__main__':
    img=Img2Array()
    base=os.path.join(os.path.dirname(__file__),'data')
    img.main(os.path.join(base,'train.txt'),os.path.join(base,'train.npy'))
    img.main(os.path.join(base,'validate.txt'),os.path.join(base,'validate.npy'))
    img.main(os.path.join(base,'test.txt'),os.path.join(base,'test.npy'))